package com.assets.Fragment;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.assets.Ip_set.Url;
import com.assets.R;
import com.assets.Scan.qrcode.util.Constant;
import com.assets.Scan.zxing.activity.CaptureActivity;
import com.assets.databinding.ActivityQueryBinding;
import com.assets.menu.SlideSideMenuExampleActivity;
import com.assets.newNHF.util.LogUtils;
import com.assets.query.QueryAdapter;
import com.assets.query.QueryData;
import com.assets.query.QueryDetailActivity;
import com.assets.room.database.MyDataBase;
import com.assets.room.entity.Asset;
import com.assets.room.entity.Dept;
import com.assets.room.entity.Place;
import com.assets.room.entity.Type;
import com.assets.util.MyOkHttp;
import com.assets.util.MyRFIDHandle;
import com.assets.util.RFIDClientUtil;
import com.google.gson.Gson;
import com.lemonade.widgets.slidesidemenu.SlideSideMenuTransitionLayout;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import okhttp3.Response;

/**
 * Created by zq on 2017/1/13.
 */

public class Query extends Fragment {
    private ActivityQueryBinding mBinding;
    private String url = "http://" + Url.IP + "/api/assetScan";
    private SlideSideMenuExampleActivity activity;
    private Handler handler;
    private String scan;
    private Runnable runGetScanData = () -> {
        getData(scan);
    };
    private List<QueryData> mDataList = new ArrayList<>();
    private QueryAdapter mAdapter = new QueryAdapter(mDataList);
    private RFIDClientUtil rfidClientUtil;
    private Map<String, String> map = new HashMap<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_query, null);
        mBinding = DataBindingUtil.bind(view);
        mDataList.clear();
        map.clear();
        initView();
        initHandle();
        initRFID();
        return mBinding.getRoot();
    }


    private void initView() {
        activity = (SlideSideMenuExampleActivity) getActivity();
        mBinding.includeTitle.opmenu.setOnClickListener(v -> {
            SlideSideMenuTransitionLayout mSlideSideMenu = (SlideSideMenuTransitionLayout) getActivity().findViewById(R.id.slide_side_menu);
            mSlideSideMenu.toggle();
        });
        mBinding.InputNumber.setFocusableInTouchMode(true);
        mBinding.InputNumber.requestFocus();
        mBinding.InputNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
//                mBinding.InputNumber.selectAll();
                scan = s.toString();
                if (!TextUtils.isEmpty(scan)) {
                    handler.removeCallbacks(runGetScanData);
                    handler.postDelayed(runGetScanData, 300);
                }
            }
        });
        mBinding.includeTitle.titleText.setText("查询");
        mBinding.scan.setOnClickListener(v -> startQrCode());
        mBinding.btnRfid.setOnClickListener(v -> {
            String rfidTitle = mBinding.btnRfid.getText().toString();
            if (rfidTitle.equals("开始读取")) {
                rfidClientUtil.read();
            } else {
                rfidClientUtil.stop();
            }
        });
        mBinding.btnDelete.setOnClickListener(view -> {
            mDataList.clear();
            mAdapter.notifyDataSetChanged();
        });
        mBinding.rcView.setLayoutManager(new LinearLayoutManager(activity));
        mBinding.rcView.setAdapter(mAdapter);
        mAdapter.setOnClickListen(integer -> {
            Intent intent = new Intent(getContext(), QueryDetailActivity.class);
            intent.putExtra("queryData", mDataList.get(integer));
            startActivity(intent);
        });
    }

    private void initRFID() {
        MyRFIDHandle myRFIDHandle = new MyRFIDHandle();
        myRFIDHandle.post(() -> {
            rfidClientUtil = new RFIDClientUtil(epc -> {
                getRfidData(epc);
            });
            rfidClientUtil.setRequestStop(() -> activity.runOnUiThread(() -> {
                mBinding.btnRfid.setText("开始读取");
            }));
            rfidClientUtil.setRequestRead(() -> activity.runOnUiThread(() -> {
                mBinding.btnRfid.setText("停止读取");
            }));
            getLifecycle().addObserver(myRFIDHandle);
            getLifecycle().addObserver(rfidClientUtil);
        });
    }

    private void initHandle() {
        if (handler == null) {
            handler = new Handler();
        }
    }

    private void getRfidData(String epc) {
        if (TextUtils.isEmpty(epc)) {
            return;
        }
        LogUtils.d(epc);
//        if (map.containsKey(epc)) {
//            return;
//        }
        map.put(epc, "");
//        activity.showDialog("数据查询中");
        Map<String, String> mapParam = new HashMap<>();
        mapParam.put("rfid", epc);

        epc = epc.replaceAll("[\n\r\t]", "");

        epc = epc.substring(0, 16);


        Map<String, Object> map1 = new HashMap<String, Object>();
        map1.put("state", "0");
        Asset asset = MyDataBase.init(activity).assetDao().queryAllById(epc);

        if (asset == null) {
            map1.put("state", "2");
            activity.showToast("不存在此资产!");
            return;
        }else {

            asset.setUserId(MyDataBase.init(activity).userDao().getNameByIds(asset.getUserId()) == null ? "暂无使用人":MyDataBase.init(activity).userDao().getNameByIds(asset.getUserId()));
            Dept deptById = MyDataBase.init(activity).deptDao().getDeptById(asset.getDeptId());
            if (deptById != null) {
                asset.setDeptId(deptById.getSimpleName());
            }
            Type allById = MyDataBase.init(activity).typeDao().getAllById(asset.getType());
            if (allById !=null) {
                asset.setType(allById.getName());
            }
            Dept deptById1 = MyDataBase.init(activity).deptDao().getDeptById(asset.getCompany());
            if (deptById1 != null) {
                asset.setCompany(deptById1.getSimpleName());
            }

//
//            if (asset.getAccountant().isEmpty() || asset.getAccountant().equals("/") && asset.getFinancialCode().isEmpty() || "/".equals(asset.getFinancialCode())) {
//
//                Place allById1 = MyDataBase.init(activity).placeDao().getAllById(asset.getPlace());
//                asset.setPlace(allById1.getName());
//
//            }else {
//                if (!asset.getAccountant().isEmpty()) {
//                    Place allByIdJiGui = MyDataBase.init(activity).placeDao().getAllById(asset.getPlace());
//                    Place allByIdJiFang = MyDataBase.init(activity).placeDao().getAllByPids(allByIdJiGui.getPid());
//                    Place dao = MyDataBase.init(activity).placeDao().getAllByPids(allByIdJiFang.getPid());
//                    asset.setPlace(dao.getName());
//                }else {
//                    Place allByIdJiGui = MyDataBase.init(activity).placeDao().getAllById(asset.getPlace());
//                    Place allByIdJiFang = MyDataBase.init(activity).placeDao().getAllByPids(allByIdJiGui.getPid());
//                    asset.setPlace(allByIdJiFang.getName());
//                }
//            }



            map1.put("state", "1");
            map1.put("asset", asset);

            Gson gson = new Gson();



            QueryData queryData = MyOkHttp.getInstance().getGson().fromJson(gson.toJson(map1), QueryData.class);
            for (int i = 0; i < mDataList.size(); i++) {
                if (mDataList.get(i).getAsset().getAssetId().equals(queryData.getAsset().getAssetId())) {

                    activity.showToast("该资产已存在列表中");
                    return;

                }
            }
            mDataList.add(queryData);
            activity.runOnUiThread(() -> mAdapter.notifyItemInserted(mAdapter.getItemCount()));
//            activity.canDialog();

        }

//        LogUtils.d(epc + Url.assetScanRfid());
//        MyOkHttp.getInstance().post(Url.assetScanRfid(), mapParam, new MyOkHttp.requestMessage() {
//            @Override
//            public void requestFail() {
//                map.remove(epc);
//                activity.showToast("连接服务器失败");
//            }
//
//            @Override
//            public void requestComplete() {
//                activity.canDialog();
//            }
//
//            @Override
//            public void requestSuccess(Response response) throws IOException {
//                String responseData = response.body().string();
//                LogUtils.d(responseData);
//                QueryData queryData = MyOkHttp.getInstance().getGson().fromJson(responseData, QueryData.class);
//                String state = queryData.getState();
//                if (TextUtils.isEmpty(state)) {
//                    activity.showToast("查询失败");
//                    return;
//                }
//                if (state.equals("2")) {
//                    activity.showToast("资产不存在");
//                    return;
//                }
//                if (queryData.getAsset() == null) {
//                    LogUtils.d("queryData.getAsset()=null");
//                    return;
//                }
//                mDataList.add(queryData);
//                activity.runOnUiThread(() -> mAdapter.notifyItemInserted(mAdapter.getItemCount()));
//            }
//        });

    }

    private void getData(String scan) {
        if (TextUtils.isEmpty(scan)) {
            return;
        }
        for (QueryData queryData : mDataList) {
            if (queryData.getAsset().getAssetNumber().equals(scan)) {
                activity.showToast("请勿重复扫码");
                mBinding.InputNumber.setText("");
                return;
            }
        }
//        if (map.containsKey(scan)) {
//            activity.showToast("请勿重复扫码");
//            mBinding.InputNumber.setText("");
//            map.clear();
//            return;
//        }
        map.put(scan, "");
//        activity.showDialog("数据查询中");

        Log.d("扫出来的是个什么玩意", "scan: " + scan);

        scan = scan.replaceAll("[\n\r\t]", "");

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("state", "0");
        Asset asset = MyDataBase.init(activity).assetDao().queryAllByIdSao(scan);
        if (asset == null) {
            map.put("state", "2");
            activity.showToast("不存在此资产!");
            return;
        }else {
            asset.setUserId(MyDataBase.init(activity).userDao().getNameByIds(asset.getUserId()) == null ? "暂无使用人":MyDataBase.init(activity).userDao().getNameByIds(asset.getUserId()));
            Dept deptById = MyDataBase.init(activity).deptDao().getDeptById(asset.getDeptId());
            if (deptById != null) {
                asset.setDeptId(deptById.getSimpleName());
            }else {
                asset.setDeptId("暂无所属地点");
            }
            Type allById = MyDataBase.init(activity).typeDao().getAllById(asset.getType());
            if (allById !=null) {
                asset.setType(allById.getName());
            }
            Dept deptById1 = MyDataBase.init(activity).deptDao().getDeptById(asset.getCompany());
            if (deptById1 != null) {
                asset.setCompany(deptById1.getSimpleName());
            }else {

            }

//            if (asset.getAccountant().isEmpty() || asset.getAccountant().equals("/") && asset.getFinancialCode().isEmpty() || "/".equals(asset.getFinancialCode())) {
//
//                Place allById1 = MyDataBase.init(activity).placeDao().getAllById(asset.getPlace());
//                asset.setPlace(allById1.getName());
//
//            }else {
//                if (!asset.getAccountant().isEmpty() && !"/".equals(asset.getAccountant())) {
//                    Place allByIdJiGui = MyDataBase.init(activity).placeDao().getAllById(asset.getPlace());
//                    Place allByIdJiFang = MyDataBase.init(activity).placeDao().getAllById(allByIdJiGui.getPid());
//                    Place dao = MyDataBase.init(activity).placeDao().getAllById(allByIdJiFang.getPid());
//                    asset.setPlace(dao.getName());
//                }/**/else {
//                    Place allByIdJiGui = MyDataBase.init(activity).placeDao().getAllById(asset.getPlace());
//                    Place allByIdJiFang = MyDataBase.init(activity).placeDao().getAllById(allByIdJiGui.getPid());
//                    asset.setPlace(allByIdJiFang.getName());
//                }
//            }

            map.put("state", "1");
            map.put("asset", asset);




            Gson gson = new Gson();

            QueryData queryData = MyOkHttp.getInstance().getGson().fromJson(gson.toJson(map), QueryData.class);
            for (int i = 0; i < mDataList.size(); i++) {
                if (mDataList.get(i).getAsset().getAssetId().equals(queryData.getAsset().getAssetId())) {
                    mBinding.InputNumber.setText("");
                    activity.showToast("该资产已存在列表中");
                    return;

                }
            }



            mDataList.add(queryData);
            activity.runOnUiThread(() -> mAdapter.notifyItemInserted(mAdapter.getItemCount()));
            mBinding.InputNumber.setText("");
//            activity.canDialog();

        }


//        Map<String, String> mapParam = new HashMap<>();
//        mapParam.put("assetNumber", scan);
//        LogUtils.d(scan + url);
//        MyOkHttp.getInstance().post(url, mapParam, new MyOkHttp.requestMessage() {
//            @Override
//            public void requestFail() {
//                map.remove(scan);
//                activity.showToast("连接服务器失败");
//            }
//
//            @Override
//            public void requestComplete() {
//                activity.canDialog();
//            }
//
//            @Override
//            public void requestSuccess(Response response) throws IOException {
//                String responseData = response.body().string();
//                LogUtils.d(responseData);
//                QueryData queryData = MyOkHttp.getInstance().getGson().fromJson(responseData, QueryData.class);
//                String state = queryData.getState();
//                if (TextUtils.isEmpty(state)) {
//                    activity.showToast("查询失败");
//                    return;
//                }
//                if (state.equals("2")) {
//                    activity.showToast("资产不存在");
//                    return;
//                }
//                mDataList.add(queryData);
//                activity.runOnUiThread(() -> mAdapter.notifyItemInserted(mAdapter.getItemCount()));
//            }
//        });

    }


    // 开始扫码
    private void startQrCode() {
        // 申请相机权限
        if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        // 申请文件读写权限（部分朋友遇到相册选图需要读写权限的情况，这里一并写一下）
        if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Constant.REQ_PERM_EXTERNAL_STORAGE);
            return;
        }
        // 二维码扫码
        Intent intent = new Intent(activity, CaptureActivity.class);
        startActivityForResult(intent, Constant.REQ_QR_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 摄像头权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    activity.showToast("请至权限中心打开本应用的相机访问权限");
                }
                break;
            case Constant.REQ_PERM_EXTERNAL_STORAGE:
                // 文件读写权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    activity.showToast("请至权限中心打开本应用的文件读写权限");
                }
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //扫描结果回调
        if (requestCode == Constant.REQ_QR_CODE && resultCode == activity.RESULT_OK) {
            Bundle bundle = data.getExtras();
            scan = bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN);
            //将扫描出的信息显示出来
            if (!TextUtils.isEmpty(scan)) {
                getData(scan);
            }
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        mBinding.InputNumber.setText("");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }
}
